﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Web.Enhancements.Rest
{
    public class HtmlFormSerializer
    {
        public HtmlFormSerializer()
        {
        }

        public string Serialize(object source)
        {
            throw new NotImplementedException();
        }

        public object Deserialize(NameValueCollection collection, Type targetType)
        {
            object result = Activator.CreateInstance(targetType);
            PropertyInfo[] props = targetType.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                bool isRequired = false;
                string bindingName = prop.Name;
                object[] attrs = prop.GetCustomAttributes(typeof(PropertyWebBinding), true);
                if (attrs != null)
                {
                    if (attrs.Length > 0)
                    {
                        PropertyWebBinding binding = (attrs[0] as PropertyWebBinding);
                        if (binding.MappingName.Length > 0)
                            bindingName = binding.MappingName;
                        isRequired = binding.IsRequired;
                    }
                }
                if (prop.PropertyType.IsArray)
                {
                    string[] textArray1 = collection.GetValues(bindingName);
                    Type type1 = prop.PropertyType.GetElementType();
                    Array array1 = Array.CreateInstance(type1, textArray1.Length);
                    for (int num2 = 0; num2 < textArray1.Length; num2++)
                    {
                        string text1 = textArray1[num2];
                        array1.SetValue(ScalarFormatter.FromString(text1, type1), num2);
                    }
                    prop.SetValue(result, array1, null);
                }
                else
                {
                    string text2 = collection[bindingName];
                    if (text2 != null)
                        prop.SetValue(result, ScalarFormatter.FromString(text2, prop.PropertyType), null);
                    else if (isRequired)
                    {
                        throw new InvalidOperationException(string.Format("Property {0} is missing.", bindingName));
                    }
                }
            }
            return result;
        }
    }
}